package common;

public class LockWaiter
{
    int waiters = 0;
    boolean used;

    public LockWaiter()
    {
    }

    public boolean waitForLock(int timeoutMs)
    {
        synchronized (this)
        {
            waiters++;
            try
            {
                NotifyWaiter waiter = new NotifyWaiter(this, timeoutMs);
                while (used)
                {
                    if (waiter.waitForNotify() == false)
                    {
                        return false;
                    }
                }
                used = true;
                return true;
            }
            finally
            {
                waiters--;
            }
        }

    }

    public boolean waitForLock()
    {
        synchronized (this)
        {
            waiters++;
            try
            {
                while (used)
                {
                    this.wait();
                }
                used = true;
                return true;
            }
            catch (InterruptedException e)
            {
                return false;
            }
            finally
            {
                waiters--;
            }
        }

    }

    public void releaseLock()
    {
        synchronized (this)
        {
            if (used)
            {
                used = false;
                if (waiters > 0)
                {
                    this.notify();
                }
            }
        }
    }

}
